package com.example.bysj.Service;
//201902104061徐中堂
import com.example.bysj.domain.authority.LoginResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
//声明一个业务处理类
@Service
public class LoginService{
    //登录方法
    public LoginResult login(String userName,String password){
        //创建一个登录结果对象
        LoginResult loginResult = new LoginResult();
        if (userName == null || userName.isEmpty()){
            loginResult.setLogin(false);
            loginResult.setResult("用户名为空");
            return loginResult;
        }
        String msg="";
        // 将用户名和密码封装到UsernamePasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        // 获取Subject实例对象
        Subject currentUser = SecurityUtils.getSubject();
        //认证
        try {
            currentUser.login(token);// 传到UserRealm类中的方法进行认证
            Session session = currentUser.getSession();
            session.setAttribute("username", userName);
            loginResult.setLogin(true);
            msg = "登陆成功";
            //捕捉各种异常
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            msg = "UnknownAccountException -- > " + e.getMessage();
        } catch (IncorrectCredentialsException e){
            msg = "IncorrectCredentialsException -- > " + e.getMessage();
        } catch (AuthenticationException e){
            e.printStackTrace();
            msg = "用户验证失败";
        } finally {
            //登录状态
            loginResult.setResult(msg);
            return loginResult;
        }
    }
    //退出登录方法
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        String name = subject.getSession().getAttribute("username").toString();
        subject.logout();
        return name;
    }
}
